#!/usr/bin/perl -w

# this script creates files with rules for tcp shaper.

BEGIN   
{
    sub getPoints{return '../../' if (!$_[1]);return '../' if (!$_[0]);return '/';}
    (my $file = __FILE__) =~ s/(\/?modules)?(\/?shaping_cbq)?\/?\w+\.pl$/&getPoints($1,$2)/e;
    $file = './' if $file eq '/';$file .= "bin";
    unshift(@INC, $file);
}

use strict;
use TWM;
use Data::Dumper;

my $xml = &readModuleConfigFile($cm{cbq_conf});
my $cbqlist = $xml->{item};
if (exists($cbqlist->{'class_rate_speed'}))
{
	$xml->{item} = copyHash($cbqlist);
	$cbqlist = $xml->{item};
}
my %items;

foreach my $key (keys(%$cbqlist))
{
	$items{"$cm{shaper_classes_dir}cbq-$cbqlist->{$key}->{id}.$key"} = 1;
	my @res = run_script("$ck{ethtool} $cbqlist->{$key}->{device} 2>/dev/null");
	my $eth_info = join("",@res);

	open(FILE,">$cm{shaper_classes_dir}cbq-$cbqlist->{$key}->{id}.$key") || (toErrorLog("Can not open file $cm{shaper_classes_dir}cbq-$cbqlist->{$key}->{id}.$key: $!") && die("Can not open file $key: $!"));
	my ($intf_speed, $intf_weight) = ($1, $1/10) if  $eth_info =~ /Speed: (\d+).b\/s/;
	my $weight = $cbqlist->{$key}->{class_rate_speed}/10;
	my $weight_dim = $cbqlist->{$key}->{class_rate_dim};
	if ($weight<1)
	{
		$weight *= 1000;
		if ($weight_dim eq 'Mbit')
		{
			$weight_dim = 'Kbit';
		}
		elsif ($weight_dim eq 'Kbit')
		{
			$weight_dim = 'b';
		}
		else
		{
			toErrorLog("Incorrect weight: $weight, $weight_dim");
			next;
		}
	}

	if (!$intf_speed)
	{
		toErrorLog("Could not get $cbqlist->{$key}->{device} speed.");
		next;
	}
	$cbqlist->{$key}->{ip} =~ s/\s+/\n/g;
	$cbqlist->{$key}->{ip} =~ s/(.+)/RULE=$1/g;
	toDebugLog("CBQ class:\n".Dumper($cbqlist->{$key}));
	print FILE "DEVICE=$cbqlist->{$key}->{device},${intf_speed}Mbit,${intf_weight}Mbit
RATE=$cbqlist->{$key}->{class_rate_speed}$cbqlist->{$key}->{class_rate_dim}
WEIGHT=$weight$weight_dim
PRIO=$cbqlist->{$key}->{prio}
$cbqlist->{$key}->{ip}";
	close FILE;
}

while (<$cm{shaper_classes_dir}*>)
{
	if (!exists($items{$_}))
	{
		toDebugLog("Delete CBQ config file: $_");
		unlink $_;
	}
}

sub copyHash
{
	my $cbqlist = shift;
	my $_cbqlist;
	$_cbqlist->{$cbqlist->{'name'}} = {
		'device' => $cbqlist->{'device'},
		'class_rate_speed' => $cbqlist->{'class_rate_speed'},
		'class_rate_dim' => $cbqlist->{'class_rate_dim'},
		'prio' => $cbqlist->{'prio'},
		'ip' => $cbqlist->{'ip'},
		'name' => $cbqlist->{'name'},
		'id' => $cbqlist->{'id'}
	};
	return $_cbqlist;

}


__END__
